package com.it.flowable.config;

import com.it.flowable.listener.AdvancedFlowableListener;
import com.it.flowable.listener.GlobalFlowListener;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.job.service.impl.asyncexecutor.AsyncJobExecutorConfiguration;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Configuration // 手动注入
public class FlowableConfig { // 可指定顺序

    @Resource
    private GlobalFlowListener globalFlowListener; // 注入监听器Bean
    @Resource
    private AdvancedFlowableListener advancedFlowableListener; // 注入监听器Bean

    @Bean
    public SpringProcessEngineConfiguration springProcessEngineConfiguration(
            DataSource dataSource,
            PlatformTransactionManager transactionManager) {

        SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
        config.setDataSource(dataSource);
        config.setTransactionManager(transactionManager);
        config.setAsyncExecutorActivate(true);
        AsyncJobExecutorConfiguration asyncConfig = config.getAsyncExecutorConfiguration();
        asyncConfig.setDefaultTimerJobAcquireWaitTime(Duration.ofSeconds(1));// 定时作业轮询间隔,
        asyncConfig.setDefaultAsyncJobAcquireWaitTime(Duration.ofSeconds(5)); // 异步作业轮询间隔
        config.setDatabaseSchemaUpdate(SpringProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);

        // 配置事件监听器
        List<FlowableEventListener> eventListeners = new ArrayList<>();
        // eventListeners.add(globalFlowListener);
        eventListeners.add(advancedFlowableListener);
        config.setEventListeners(eventListeners);

        return config;
    }
}